<template>
  <el-card class="comment-card">
    <template #header>
      <div class="card-header">
        <div class="user-info">
          <el-avatar :size="32" :src="comment?.user_avatar || defaultAvatar" />
          <span class="username">{{ comment?.user_name || '匿名用户' }}</span>
        </div>
        <div class="comment-time">{{ formatTime(comment.created_at) }}</div>
      </div>
    </template>
    
    <div class="comment-content">{{ comment.content }}</div>
    
    <template #footer>
      <div class="comment-actions">
        <el-button 
          :type="comment.isLiked ? 'danger' : 'info'" 
          size="small" 
          @click="handleLike"
          :loading="likeLoading"
        >
          <el-icon><Star /></el-icon>
          {{ comment.likes || 0 }}
        </el-button>
        <el-button
          v-if="showDelete"
          type="danger"
          size="small"
          @click="handleDelete"
          :loading="deleteLoading"
        >
          删除
        </el-button>
      </div>
    </template>
  </el-card>
</template>

<script setup>
import { ref } from 'vue';
import { Star } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { commentAPI } from '@/api/comments';

const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

const props = defineProps({
  comment: {
    type: Object,
    required: true
  },
  showDelete: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update-comment', 'delete-comment']);

const likeLoading = ref(false);
const deleteLoading = ref(false);

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString();
};

const handleLike = async () => {
  try {
    likeLoading.value = true;
    
    // 1. 发送点赞请求
    const  data  = await commentAPI.likeComment(props.comment.id);
    
    // 2. 数据合并策略（关键修复）
    const updatedComment = {
      ...props.comment,    // 保留原有数据
      ...data,             // 合并更新字段
      // 强制转换时间戳
      created_at: data.created_at || Date.now(),
      // 保留用户信息
      user: data.user || props.comment.user 
    };
    
    // 3. 安全传递数据
    emit('update-comment', updatedComment);

  } catch (error) {
    // 4. 增强错误处理
    console.error('点赞失败详情:', error);
    ElMessage.error(error.response?.data?.message || `点赞失败 (${error.code || '未知错误'})`);
    
    // 5. 回滚点赞状态
    emit('update-comment', {
      ...props.comment,
      likes: props.comment.likes - 1,
      isLiked: false
    });
    
  } finally {
    likeLoading.value = false;
  }
};

const handleDelete = async () => {
  try {
    deleteLoading.value = true;
    await commentAPI.deleteComment(props.comment.id);
    emit('delete-comment', props.comment.id);
    ElMessage.success('删除成功');
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '删除失败');
  } finally {
    deleteLoading.value = false;
  }
};
</script>

<style scoped>
/* 保持原有样式不变 */
.comment-card {
  margin-bottom: 16px;
  transition: box-shadow 0.3s;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-weight: 500;
}

.comment-time {
  color: #999;
  font-size: 0.9em;
}

.comment-content {
  line-height: 1.6;
  margin: 12px 0;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>